package cn.sheep.zkapi;

import org.apache.zookeeper.*;
import org.junit.Test;

import java.io.IOException;
import java.util.List;

/**
 * author: sheep.Old
 * qq: 64341393
 * Created 2018/5/31
 */
public class ZookeeperApi {


    static final String ZKSERVER = "demo01:2181,demo02:2181,demo03:2181";
    static final int TIMEOUT = 2000;


    /**
     * 增加节点
     */
    @Test
    public void testCreate() throws IOException, KeeperException, InterruptedException {
        // 连接zk
        ZooKeeper zk = new ZooKeeper(ZKSERVER, TIMEOUT, null);

        zk.create("/grils", "caiyehua".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        // 释放
        zk.close();
    }


    /**
     * 修改节点数据
     */
    @Test
    public void testSet() throws IOException, KeeperException, InterruptedException {
        // 连接zk
        ZooKeeper zk = new ZooKeeper(ZKSERVER, TIMEOUT, null);

        zk.setData("/grils", "chizecaiyehua".getBytes(), -1);
        zk.close();
    }


    /**
     * 查询节点
     */
    @Test
    public void testList() throws IOException, KeeperException, InterruptedException {

        ZooKeeper zk = new ZooKeeper(ZKSERVER, TIMEOUT, null);
        //查询所有节点名称
        List<String> list = zk.getChildren("/servers", false);
        for (String s : list) {
            System.out.print("key = " + s);
            //查询所有节点数据
            byte[] data = zk.getData("/servers/" + s, null, null);
            System.out.println("   data: = " + new String(data));
        }
        zk.close();
    }


    /**
     * delete删除节点
     * 只能删除单个节点，节点下面不能有子节点
     */
    @Test
    public void testDelete() throws IOException, KeeperException, InterruptedException {
        ZooKeeper zk = new ZooKeeper(ZKSERVER, TIMEOUT, null);

        zk.delete("/grils", -1);

        zk.close();
    }


    /**
     * 删除节点及其子节点
     */
    @Test
    public void testRecursive() throws IOException, KeeperException, InterruptedException {

        ZooKeeper zk = new ZooKeeper(ZKSERVER, TIMEOUT, null);

        rmr("/servers", zk);

        zk.close();
    }


    public static void rmr(String path, ZooKeeper zk) throws KeeperException, InterruptedException {
        // 先查询要删除的节点下面是否还有子节点，如果有子节点继续查， 如果没有呢？删除

        List<String> children = zk.getChildren(path, false);

        for (String child : children) {
            rmr(path+"/"+child, zk);
        }
        // 如果没有子节点删除自己
        zk.delete(path, -1);
    }


}
